var express = require("express");
var router = express.Router();
var { userModel } = require("../model/modellx");
const nodemailer = require("nodemailer");
const jwt = require('jsonwebtoken');
const tencentcloud = require("tencentcloud-sdk-nodejs");
const { randomCode } = require("../tools/sendCode");


/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});

const { randomCode, sendCode } = require("../tools/sendCode");
// 验证码
router.post("/SMS", async (req, res) => {
  let {phone } = req.body;
  console.log(phone);

  let code = randomCode(4); //生成6位数字随机验证码
  sendCode(phone, code, function (success) {
    if (success) {
      res.send({
        code: 200,
        msg: "验证码发送成功",
        data: code,
      });
    } else {
      res.send("短信验证码发送失败");
    }
  });
});

//登录
router.post("/login", async (req, res) => {
  let { code, phone } = req.body;
  console.log(phone);
let result = await userModel.findOne({ phone });
  if (result) {
    let data = await userModel.find({ phone: phone });
    res.send({
      code: 200,
      Toast: "登录成功",
      data,
    });
  } else {
    res.send({
      code: 400,
      Toast: "登录失败",
    });
  }
});

// 邮箱验证
router.post("/email", async (req, result) => {
  let { email } = req.body;
  console.log(email);
  let code = randomCode(6); //生成6位数的验证码
  //开启一个 SMTP 连接池
  var transport = nodemailer.createTransport({
    host: "smtp.qq.com", //QQ邮箱的 smtp 服务器地址
    secure: true, //使用 SSL 协议
    secureConnection: false, //是否使用对 https 协议的安全连接
    port: 465, //QQ邮件服务所占用的端口
    auth: {
      user: "1106607092@qq.com", //开启 smtp 服务的发件人邮箱，用于发送邮件给其他人
      pass: "ahbtjnlxtesxijib", //SMTP 服务授权码
    },
  });

  //邮箱配置
  var mailOption = {
    from: "1106607092@qq.com", //发件人
    to: email, //收件人
    subject: "小牛商店", //标题
    html: `<b>验证码为：${code}</br>请在5分钟之内完成验证</b>`, //正文，可使用 HTML 格式进行渲染
  };
  //发送邮件
  await transport.sendMail(mailOption, (err, res) => {
    console.log(err);
    if (err) {
      //执行错误
      result.send({
        state: 400,
        msg: "发送失败,请检查邮箱是否正确",
      });
    } else {
      result.send({
        state: 200,
        msg: "发送成功",
        code,
      }); //执行成功， 会返回响应体内容。
    }
    transport.close(); // 如果没用，则关闭连接池
  });
});

//登录
router.post("/getEmail", async (req, res) => {
  let { email } = req.body;
  console.log(email);
  let result = await userModel.findOne({ email });
  console.log(result);
  if (result) {
    let data = await userModel.find({ email: email });
    res.send({
      code: 200,
      Toast: "登录成功",
      data,
    });
  } else {
    res.send({
      code: 400,
      Toast: "登录失败",
    });
  }
});

// 人脸识别
router.post("/faceLogin", async (req, res) => {
  //获取前端传来的base64
  let b64 = req.body.b64;
  const IaiClient = tencentcloud.iai.v20200303.Client;

  try {
    const clientConfig = {
      credential: {
        //自己的腾讯secretId
        secretId: "AKID0uiOvEKGzYt43pNhwzoQoytaaVDiz2rT",
        //自己的腾讯密匙
        secretKey: "UAcrthGbjdvBF8sY2IVUKxRo4831su6C",
      },

      region: "ap-beijing", //地域参数（华北地区北京）+
      profile: {
        httpProfile: {
          endpoint: "iai.tencentcloudapi.com",
        },
      },
    };

    const client = new IaiClient(clientConfig);

    const params = {
      GroupIds: [
        //你创建的人员库ID
        "face",
      ],
      Image: b64, //图片的base64格式编码
      NeedPersonInfo: 1, //是否返回人员具体信息。0 为关闭，1 为开启。默认为 0。
      QualityControl: 0, //图片质量控制。 0: 不进行控制； 1:较低的质量要求
      FaceMatchThreshold: 85, //人脸对比度设置为大于85才可
    };
    // console.log(params, 'params');
    let doc = await client.SearchFaces(params);
    // doc为人脸识别后的返回信息
    // console.log(doc, 'doc');
    if (doc.Results[0].Candidates.length != 0) {
      //表示当前人脸库有该人员
      let personName = doc.Results[0].Candidates[0].PersonName; //拿到该人员的名称
      console.log(personName, "personNume");
      res.send({ code: 200, msg: "登录成功！" });
      let user = await userModel.find({ facename: personName });
      if (user.length != 0) {
        //生成token
        let token = jwt.sign({ name: personName }, "face", { expiresIn: "1d" });
        res.send({
          code: 200,
          msg: "登录成功！",
          token,
          _id: user[0]._id,
        });
      }
    } else {
      res.send({
        code: 401,
        msg: "人脸库无此人！",
      });
      return false;
    }
  } catch (err) {
    console.log(err);
  }
});

//注册
router.post("/register", async (req, res) => {
  let { username, phone, password } = req.body;
  console.log(req.body);
  let Phone = await userModel.findOne({ phone });
  let Name = await userModel.findOne({ name:username });
  let Pwd=await userModel.findOne({password});
  if (Name) {
    res.send({
      code: 400,
      msg: "该用户名已被绑定",
    });
    return;
  }
  if (Phone) {
    res.send({
      code: 400,
      msg: "该手机号已被绑定",
    });
    return;
  }if (Pwd) {
    res.send({
      code: 400,
      msg: "该用户名已被绑定",
    });
    return;
  }
  else {
    //用户不存在进行注册
    userModel.create({name:username,phone:phone,password:password,age:18,sex:1,email:"1106607092@qq.com"});
    res.send({
      code: 200,
      msg: "注册成功! 去登入",
    });
  }
});



// 双token
// 密钥，实际应用中应从环境变量读取
const secretKey = 'your_secret_key';
// 登录接口
router.post('/Towlogin', async (req, res) => {
  const { username, password } = req.body;
  console.log(username, password);

  try {
    // 验证用户名和密码
    const user = await userModel.findOne({ name: username, password: password });
    console.log(1234567);
    console.log(user);

    if (user) {
      // 生成访问令牌和刷新令牌
      const accessToken = jwt.sign({ userId: user.id }, secretKey, { expiresIn: '15m' });
      const refreshToken = jwt.sign({ userId: user.id }, secretKey, { expiresIn: '7d' });

      res.json({
        code: 200,
        msg: '登录成功',
        data: user,
        accessToken,
        refreshToken
      });
    } else {
      console.log(123456);
      res.json({
        code: 400,
        msg: '登录失败'
      });
    }
  } catch (error) {
    console.error('Error during login:', error);
    res.status(500).json({
      code: 500,
      msg: '服务器错误'
    });
  }
});

// 受保护的资源
router.get('/protected', verifyToken, (req, res) => {
  res.json({ message: 'This is a protected resource', user: req.user });
});

// 刷新访问令牌
router.post('/refresh-token', (req, res) => {
  const { refreshToken } = req.body;

  // 验证刷新令牌
  jwt.verify(refreshToken, secretKey, (err, decoded) => {
    if (err) {
      return res.status(401).json({ message: 'Invalid refresh token' });
    }

    // 生成新的访问令牌
    const newAccessToken = jwt.sign({ userId: decoded.userId }, secretKey, { expiresIn: '15m' });

    res.json({ accessToken: newAccessToken });
  });
});
// 中间件：验证访问令牌
function verifyToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (token == null) {
    return res.sendStatus(401);
  }

  jwt.verify(token, secretKey, (err, decoded) => {
    if (err) {
      return res.sendStatus(403);
    }
    req.user = decoded;
    next();
  });
}

// gitee登录
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/gitee-token', async (req, res) => {
  try {
    const clientId = 'bbe1345c39d503ff57c4755464029e516c98fb833175c555d95a38e7438778ad'; // 客户端ID
    const clientSecret = 'e64a4671211fb648184f318013901d69736395026e88fba717506e44816f9e1b'; // 客户端密钥
    const code = req.body.code; // 从请求体中获取的code
    const redirectUri = 'http://localhost:5173/home'; // 回调地址
    console.log(code)
    // 获取token
    const tokenResponse = await axios.post('https://gitee.com/oauth/token', {
      client_id: clientId,// 客户端ID
      client_secret: clientSecret,// 客户端密钥
      code: code,// 授权码
      redirect_uri: redirectUri,// 回调地址
      grant_type: 'authorization_code'// 授权类型
    });
    console.log(tokenResponse)
    // 返回结果给客户端
    res.status(200).json(tokenResponse.data);
  } catch (error) {
    // 错误处理
    console.error(error);
    res.status(500).send('Error fetching Gitee token.');
  }
});

module.exports = router;
